package org.FaPe3D.core.viewports
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.events.Event;
	import flash.utils.setTimeout;
	
	import org.FaPe3D.Adapter;
	import org.FaPe3D.core.events.EventManager;
	
	public class ExternalElements extends EventManager
	{
		private var _id:String;
		private var _xml:XML;
		private var _bulkLoader:BulkLoader;
		public static var TYPE_ELEMENTS:String = 'External';
		public static var TYPE_FINAL:String = 'DisplayObject3D';
		
		
		public function ExternalElements(id:String, xml:XML)
		{
			_id = id;
			_xml = xml;	
			
			// cretae bulkLoader instance
			_bulkLoader = new BulkLoader('FAPE3D_' + TYPE_ELEMENTS +'_' + _xml.@id);
			var i:Number=0;
			while(i < _xml..@type.length())
			{
				if(_xml..@type[i] == TYPE_ELEMENTS)
				{
					_bulkLoader.add
					(  
						Adapter.getAdapter(_id).settings.setting['path.elements'].replace('{0}', _xml..@type[i]..parent().@name)
						,
						{ type:"xml", id: _xml..@type[i].parent().@id+'' }
					);
					
				}
				i++;
			}
			
			if(_bulkLoader._itemsTotal)
			{
				// start loading file(s)
				_bulkLoader.start();
				_bulkLoader.addEventListener(BulkProgressEvent.COMPLETE, pars);	
			}else
			{
				setTimeout(function(){dispatchEvent(new Event( Event.COMPLETE ) );}, 1);
			}
		}
	
		private function pars(e:BulkProgressEvent)
		{
			
			var i:Number=0;
			while(i < _xml..@type.length())
			{
				if(_xml..@type[i] == TYPE_ELEMENTS)
				{	
					_xml..@type[i] = TYPE_FINAL;
					_xml..@type[i].parent().appendChild(
					_bulkLoader.getXML(_xml..@type[i].parent().@id+'')
											  );
				}
				i++;
			}
			
			_bulkLoader.removeAll();
			
			// parsing compeleted
			dispatchEvent(new Event( Event.COMPLETE ) );
		}
		
		
		public function get xml():XML
		{
			return _xml;
		}
		
	}
}